<template>
	<view class="page-container">
		<!-- 顶部装饰 -->
		<view class="top-decoration"></view>

		<!-- 标题区 -->
		<view class="page-header">
			<view class="title-icon">
				<uni-icons type="person-add" size="40rpx" color="#000"></uni-icons>
			</view>
			<text class="title">美食家注册</text>
			<text class="subtitle">加入我们，发现更多美味</text>
		</view>

		<!-- 表单容器 -->
		<view class="form-card">
			<!-- 用户名 -->
			<view class="form-item">
				<view class="item-label">
					<uni-icons type="person" size="24rpx" color="#ff7d00"></uni-icons>
					<text class="label-text">用户名</text>
					<text class="required">*</text>
				</view>
				<input type="text" v-model="userForm.name" placeholder="3-12位字母/数字" class="input-item"
					@blur="validateField('name')">
				</input>
				<uni-icons type="clear" size="24rpx" color="#ccc" class="clear-icon" v-if="userForm.name"
					@click="userForm.name = ''"></uni-icons>
			</view>
			<text class="error-text" v-if="errors.name">{{ errors.name }}</text>

			<!-- 密码 -->
			<view class="form-item">
				<view class="item-label">
					<uni-icons type="lock" size="24rpx" color="#ff7d00"></uni-icons>
					<text class="label-text">密码</text>
					<text class="required">*</text>
				</view>
				<input :type="showPwd ? 'text' : 'password'" v-model="userForm.password" placeholder="6-12位字母/数字"
					class="input-item" @blur="validateField('password')"></input>
				<uni-icons :type="showPwd ? 'eye-slash' : 'eye'" size="24rpx" color="#ccc" class="toggle-icon"
					@click="showPwd = !showPwd"></uni-icons>
			</view>
			<text class="error-text" v-if="errors.password">{{ errors.password }}</text>

			<!-- 确认密码 -->
			<view class="form-item">
				<view class="item-label">
					<uni-icons type="lock" size="24rpx" color="#ff7d00"></uni-icons>
					<text class="label-text">确认密码</text>
					<text class="required">*</text>
				</view>
				<input :type="showPwd2 ? 'text' : 'password'" v-model="userForm.password2" placeholder="再次输入密码"
					class="input-item" @blur="validateField('password2')"></input>
				<uni-icons :type="showPwd2 ? 'eye-slash' : 'eye'" size="24rpx" color="#ccc" class="toggle-icon"
					@click="showPwd2 = !showPwd2"></uni-icons>
			</view>
			<text class="error-text" v-if="errors.password2">{{ errors.password2 }}</text>

			<!-- 手机号 -->
			<view class="form-item">
				<view class="item-label">
					<uni-icons type="phone" size="24rpx" color="#ff7d00"></uni-icons>
					<text class="label-text">手机号</text>
					<text class="required">*</text>
				</view>
				<input type="number" v-model="userForm.phone" placeholder="11位手机号" class="input-item"
					@blur="validateField('phone')"></input>
				<uni-icons type="clear" size="24rpx" color="#ccc" class="clear-icon" v-if="userForm.phone"
					@click="userForm.phone = ''"></uni-icons>
			</view>
			<text class="error-text" v-if="errors.phone">{{ errors.phone }}</text>

			<!-- 昵称 -->
			<view class="form-item">
				<view class="item-label">
					<uni-icons type="star" size="24rpx" color="#ff7d00"></uni-icons>
					<text class="label-text">昵称</text>
				</view>
				<input type="text" v-model="userForm.nickName" placeholder="可选" class="input-item"></input>
				<uni-icons type="clear" size="24rpx" color="#ccc" class="clear-icon" v-if="userForm.nickName"
					@click="userForm.nickName = ''"></uni-icons>
			</view>

			<!-- 头像 -->
			<view class="form-item avatar-item">
				<view class="item-label">
					<uni-icons type="camera" size="24rpx" color="#ff7d00"></uni-icons>
					<text class="label-text">头像</text>
				</view>
				<view class="avatar-upload">
					<view class="upload-btn" @click="chooseImage">
						<uni-icons type="plus" size="30rpx" color="#999"></uni-icons>
						<text>选择头像</text>
					</view>
					<view class="avatar-preview-container" v-if="userForm.avatar">
						<image :src="userForm.avatar" class="avatar-preview" mode="aspectFill"></image>
						<uni-icons type="close" size="24rpx" color="#fff" class="avatar-remove"
							@click="userForm.avatar = ''"></uni-icons>
					</view>
				</view>
			</view>
		</view>

		<!-- 按钮区域 -->
		<view class="btn-group">
			<button class="submit-btn" @click="onSubmit" :loading="isSubmitting">
				<uni-icons type="checkmark" size="24rpx" color="#fff" v-if="!isSubmitting"></uni-icons>
				<text>提交注册</text>
			</button>
			<button class="reset-btn" @click="onReset">
				<uni-icons type="refresh" size="24rpx" color="#666"></uni-icons>
				<text>重置</text>
			</button>
		</view>

		<!-- 底部提示 -->
		<view class="bottom-tip">
			<text>已有账号？</text>
			<text class="login-link" @click="toLogin">立即登录</text>
		</view>
	</view>
</template>

<script>
	import * as UserAPI from '@/api/user.js';
	import {
		setStorageUser
	} from '@/utils/storage.js';
	import * as FileAPI from "@/api/file.js";

	export default {
		data() {
			return {
				userForm: {
					name: '',
					password: '',
					password2: '',
					phone: '',
					avatar: '',
					nickName: ''
				},
				errors: {},
				showPwd: false,
				showPwd2: false,
				isSubmitting: false,
				// 验证规则
				rules: {
					name: [{
							required: true,
							message: '请输入用户名'
						},
						{
							pattern: /^[a-z0-9]{3,12}$/i,
							message: '3-12位字母或数字'
						}
					],
					password: [{
							required: true,
							message: '请输入密码'
						},
						{
							pattern: /^[a-z0-9]{6,12}$/i,
							message: '6-12位字母或数字'
						}
					],
					password2: [{
							required: true,
							message: '请确认密码'
						},
						(value) => value === this.userForm.password || '两次密码不一致'
					],
					phone: [{
							required: true,
							message: '请输入手机号'
						},
						{
							pattern: /^1[3-9]\d{9}$/,
							message: '请输入有效手机号'
						}
					]
				}
			};
		},
		methods: {
			// 验证单个字段
			validateField(field) {
				this.errors[field] = '';
				const rules = this.rules[field];
				if (!rules) return true;

				for (const rule of rules) {
					if (rule.required && !this.userForm[field]) {
						this.errors[field] = rule.message;
						return false;
					}
					if (rule.pattern && !rule.pattern.test(this.userForm[field])) {
						this.errors[field] = rule.message;
						return false;
					}
					if (typeof rule === 'function') {
						const result = rule(this.userForm[field]);
						if (result !== true) {
							this.errors[field] = result;
							return false;
						}
					}
				}
				return true;
			},

			// 整体验证
			validateForm() {
				this.errors = {};
				return Object.keys(this.rules).every(field => this.validateField(field));
			},

			// 选择并上传头像
			// 选择并上传头像（修改注册页中的方法）
			chooseImage() {
			  uni.chooseImage({
			    count: 1, // 仅选1张
			    sizeType: ['compressed'], // 优先压缩图，减少上传时间
			    sourceType: ['album', 'camera'], // 支持相册和相机
			    success: (res) => {
			      const tempFilePath = res.tempFilePaths[0]; // 获取临时路径
			      uni.showLoading({ title: '上传中...' });
			
			      // 调用修复后的uploadFile方法
			      FileAPI.uploadFile(tempFilePath)
			        .then(url => {
			          // 直接拿到图片URL，赋值给表单
			          this.userForm.avatar = url;
			          uni.hideLoading();
			          uni.showToast({ title: '头像上传成功' });
			        })
			        .catch(err => {
			          uni.hideLoading();
			          uni.showToast({ title: err.message, icon: 'none' });
			          console.error('头像上传失败：', err);
			        });
			    },
			    fail: (err) => {
			      uni.showToast({ title: '选择图片失败', icon: 'none' });
			    }
			  });
			},

			// 提交表单
			onSubmit() {
				if (!this.validateForm()) return;

				this.isSubmitting = true;
				const user = {
					...this.userForm
				};
				delete user.password2;

				UserAPI.register(user)
					.then(result => {
						if (result?.data) {
							setStorageUser(result.data.user);
							uni.showToast({
								title: '注册成功'
							});
							setTimeout(() => uni.reLaunch({
								url: "/pages/user/login"
							}), 1500);
						} else {
							uni.showToast({
								title: '数据异常',
								icon: 'none'
							});
						}
					})
					.catch(() => uni.showToast({
						title: '注册失败',
						icon: 'none'
					}))
					.finally(() => this.isSubmitting = false);
			},

			// 重置表单
			onReset() {
				this.userForm = {
					name: '',
					password: '',
					password2: '',
					phone: '',
					avatar: '',
					nickName: ''
				};
				this.errors = {};
				this.showPwd = this.showPwd2 = false;
			},

			// 前往登录页
			toLogin() {
				uni.navigateTo({
					url: "/pages/user/login"
				});
			}
		}
	};
</script>

<style lang="scss" scoped>
	.page-container {
		padding: 20rpx;
		background-color: #fff8f0;
		min-height: 100vh;
		box-sizing: border-box;
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
	}

	// 顶部装饰
	.top-decoration {
		height: 200rpx;
		background: linear-gradient(135deg, #ff9d2e, #ff6b2e);
		border-bottom-left-radius: 50% 20%;
		border-bottom-right-radius: 50% 20%;
		margin: -20rpx -20rpx 0;
	}

	// 标题区域
	.page-header {
		text-align: center;
		padding: 50rpx 0 30rpx;
		color: #000;
		position: relative;
		margin-top: -150rpx;

		.title-icon {
			width: 80rpx;
			height: 80rpx;
			background-color: rgba(255, 255, 255, 0.2);
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			margin: 0 auto 20rpx;
		}

		.title {
			font-size: 36rpx;
			font-weight: 600;
			display: block;
			margin-bottom: 10rpx;
			letter-spacing: 1rpx;
		}

		.subtitle {
			font-size: 24rpx;
			opacity: 0.9;
		}
	}

	// 表单卡片
	.form-card {
		background-color: #fff;
		border-radius: 20rpx;
		padding: 30rpx 20rpx;
		box-shadow: 0 5rpx 15rpx rgba(255, 125, 0, 0.1);
		margin-bottom: 40rpx;
	}

	// 表单项
	.form-item {
		display: flex;
		align-items: center;
		padding: 25rpx 0;
		border-bottom: 1px solid #f5f5f5;

		&:last-child {
			border-bottom: none;
		}

		.item-label {
			width: 150rpx;
			display: flex;
			align-items: center;
			font-size: 28rpx;
			color: #333;
			font-weight: 500;

			.label-text {
				margin-left: 10rpx;
			}

			.required {
				color: #ff4d4f;
				margin-left: 5rpx;
			}
		}

		.input-item {
			flex: 1;
			height: 60rpx;
			line-height: 60rpx;
			font-size: 28rpx;
			color: #333;
			padding: 0 10rpx;
			letter-spacing: 0.5rpx;
		}

		.clear-icon,
		.toggle-icon {
			margin: 0 10rpx;
		}
	}

	// 错误提示
	.error-text {
		color: #ff4d4f;
		font-size: 24rpx;
		padding-left: 150rpx;
		margin: -15rpx 0 10rpx;
		min-height: 30rpx;
	}

	// 头像上传
	.avatar-item {
		align-items: flex-start;
		padding: 25rpx 0;

		.avatar-upload {
			flex: 1;
			display: flex;
			align-items: center;
			gap: 20rpx;
		}

		.upload-btn {
			width: 120rpx;
			height: 120rpx;
			border: 2rpx dashed #ddd;
			border-radius: 10rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			color: #999;
			font-size: 24rpx;
		}

		.avatar-preview-container {
			width: 120rpx;
			height: 120rpx;
			border-radius: 10rpx;
			position: relative;
			overflow: hidden;
		}

		.avatar-preview {
			width: 100%;
			height: 100%;
		}

		.avatar-remove {
			position: absolute;
			right: -5rpx;
			top: -5rpx;
			width: 30rpx;
			height: 30rpx;
			background-color: rgba(0, 0, 0, 0.5);
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}

	// 按钮组
	.btn-group {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
		padding: 0 20rpx;

		button {
			height: 90rpx;
			line-height: 90rpx;
			font-size: 30rpx;
			border-radius: 45rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border: none;
			font-weight: 500;
		}

		.submit-btn {
			background: linear-gradient(90deg, #ff9d2e, #ff6b2e);
			color: #fff;
			box-shadow: 0 5rpx 15rpx rgba(255, 125, 0, 0.3);

			uni-icons {
				margin-right: 10rpx;
			}
		}

		.reset-btn {
			background-color: #fff;
			color: #666;
			border: 1px solid #eee;

			uni-icons {
				margin-right: 10rpx;
			}
		}
	}

	// 底部提示
	.bottom-tip {
		text-align: center;
		margin-top: 40rpx;
		font-size: 26rpx;
		color: #666;

		.login-link {
			color: #ff7d00;
			margin: 0 5rpx;
			text-decoration: underline;
			font-weight: 500;
		}
	}
</style>